package omq.utils;

import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import omq.api.logger.*;

public class FileUtil 
{
	// ------------------------------------------------------------
	// check if a file/folder exists
	// ------------------------------------------------------------
	public static boolean checkIfFileExist(String filename)
	{
		File f = new File(filename);
	    boolean exists = f.exists();
	    
	    String msgtmp;
	    if (f.isDirectory())
	    	msgtmp= "directory";
	    else
	    	msgtmp= "file";
	    
	    if (!exists) 
	    // File or directory doesnt exists
	    {
		    OMQLogger.getInstance().error(msgtmp+" "+filename+" doesn't exist, cannot execute.");
		    return false;
	    }
	    else
	    {
			OMQLogger.getInstance().info(msgtmp+" "+filename+" exists");
	    	return true;
	    }
	}
	
	
	// ------------------------------------------------------------
	// check if a file/path is a directory
	// ------------------------------------------------------------
	public static boolean checkIfFileIsDirectory(String filename)
	{
		File f = new File(filename);
	    
	    if (f.isDirectory())
	    	return true;
	    else
	    	return false;
	}

	
	// ------------------------------------------------------------
	// check if a file size is more than a given number (in kilobytes)
	// ------------------------------------------------------------
	public static boolean checkIfFileSizeIsMoreThan(String filename,int maxFileSize)
	{
		long length = (new File(filename)).length()+1024;
		
	    OMQLogger.getInstance().info("max file size is "+maxFileSize+" kilobytes, current file size is "+length/1024+" kilobytes");
	    
	    if ((length/1024) > maxFileSize) 
	    // File or directory doesnt exists
	    {
		    OMQLogger.getInstance().error("file size is too big, max file size is "+maxFileSize+" kilobytes");
		    return false;
	    }
	    else
	    {
	    	OMQLogger.getInstance().debug("file size is acceptable.");
	    	return true;
	    }
	}
	
	// ------------------------------------------------------------
	// check if a directory exists and if not - create it
	// ------------------------------------------------------------
	public static boolean createDirectoryIfDoesntExist(String directory)
	{
		if (!checkIfFileExist(directory))
		{
			OMQLogger.getInstance().info("directory "+directory+" doesnt exist, creating it");
			return ((new File(directory)).mkdir());
		}
		return true;
	}

	// ------------------------------------------------------------
	// rename / move 1 file
	// ------------------------------------------------------------
	public static boolean moveFile(File srcFile, File tgtFile) 
	{
		OMQLogger.getInstance().info("moving "+srcFile.getPath()+" to "+tgtFile.getPath());
        return srcFile.renameTo(tgtFile);
	}
	
	// ------------------------------------------------------------
	// move files (just files, not directories)
	// from source folder to target folder
	// returns the number of files moved
	// ------------------------------------------------------------
	public static int moveFiles(File srcFolder, File tgtFolder)
	{
		int filesToMove = 0;
		File[] fileList = FileUtil.listFilesInFolder(srcFolder);
		OMQLogger.getInstance().info("there are "+fileList.length+ " files to move in "+srcFolder.getPath());
		OMQLogger.getInstance().info("moving them to "+tgtFolder.getPath());
		filesToMove = fileList.length;
		boolean oneMoveFailed = false;
		String oneMoveFailedStr = null;
		
		// ------------------------------------------------------------
		// moving all files to processing folder
		// ------------------------------------------------------------
		for (int i=0; i<fileList.length; i++)
		{
			File srcFile = fileList[i];
			File tgtFile = new File(addSlashInFilename(tgtFolder.getPath())+srcFile.getName());
			
			
			if (!FileUtil.moveFile(srcFile,tgtFile))
			{
				OMQLogger.getInstance().error("failed to move the file "+srcFile.getPath());
				oneMoveFailed = true;
				oneMoveFailedStr = srcFile.getPath();
			}
		}		
		if (oneMoveFailed)
		{
			OMQLogger.getInstance().error("failed to move the file "+oneMoveFailedStr);
			OMQLogger.getInstance().error("going back to sleep to avoid infinite loop, will send moved files in the next run");
			filesToMove=0;
		}
		return filesToMove;
	}
	
	// ------------------------------------------------------------
	// add slash to ending of file (folder) if it isn't there
	// turn c:/temp to c:/temp/ always
	// ------------------------------------------------------------
	public static String addSlashInFilename(String filename)
	{
		if (new Character(filename.charAt(filename.length()-1)).compareTo(new Character('/')) != 0)
		{
			return filename+"/";
		}
		else
		{
			return filename;
		}
	}
	
	// -----------------------------------------------------------------
	// return a list of files (just files, not directories) in a folder
	// -----------------------------------------------------------------
	public static File[] listFilesInFolder(File folder)
	{
		FileFilter fileFilter = new FileFilter() 
		{
			public boolean accept(File file) 
			{
				return !file.isDirectory();
			}
		};
		return folder.listFiles(fileFilter); 
	}

	//TODO DELETE THIS METHOD 
	// IT SHOULD BE IN THE OMQAPI project / package
	// ----------------------------------------------------------------
	// return current time as a string
	// use like : FileUtil.time("yyyy-MM-dd_HHmmss_")
	// ----------------------------------------------------------------
	public static String time(String dateFormat) 
	{
		    Calendar cal = Calendar.getInstance();
		    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		    return sdf.format(cal.getTime());
	}

}